package com.example.lxj.system.controller;

import com.example.lxj.base.annoation.NoNeedLogin;
import com.example.lxj.base.controller.BaseController;
import com.example.lxj.base.entity.AjaxRes;
import com.example.lxj.system.entity.SysUser;
import com.example.lxj.system.service.ISysLoginService;
import com.example.lxj.system.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 登录验证
 */
@RestController
public class SysLoginController extends BaseController
{
    @Autowired
    private ISysLoginService loginService;

    @Autowired
    private ISysMenuService sysMenuService;

    /**
     * 登录方法
     * 
     * @param sysUser 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    @NoNeedLogin
    public AjaxRes login(@RequestBody SysUser sysUser)
    {
        AjaxRes ajax = AjaxRes.success();
        // 生成令牌
        String token = loginService.login(sysUser);
        ajax.put("msg","登录成功");
        ajax.put("token", token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public AjaxRes getInfo(@RequestHeader("token") String token)
    {
        // 根据用户token获取用户信息
        SysUser sysUser = loginService.getSysUserByUserToken(token);
        Map<String, Object> menuListByUserId = sysMenuService.getMenuListByUserId(sysUser.getUserId());
        AjaxRes ajax = AjaxRes.success();
        ajax.put("user", sysUser);
        ajax.put("permissions",menuListByUserId.get("permission"));
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("/getRouters")
    public AjaxRes getRouters(@RequestHeader("token") String token)
    {
        // 根据用户token获取用户信息
        SysUser sysUser = loginService.getSysUserByUserToken(token);
        Map<String, Object> menuListByUserId = sysMenuService.getMenuListByUserId(sysUser.getUserId());
        return AjaxRes.success(menuListByUserId);
    }

    /**
     * 退出登录
     */
    @GetMapping("/exitLogin")
    public AjaxRes exitLogin(@RequestHeader("token") String token){
        SysUser sysUser = loginService.getSysUserByUserToken(token);
        return toAjax(loginService.exitLogin(sysUser.getUserId()));
    }
}
